package ro.gateway.aida.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.admin.ActObjsOptsConst;
import ro.gateway.aida.admin.ActivityObjectsOptions;
import ro.gateway.aida.admin.PropertyListDB;
import ro.gateway.aida.admin.PropertyListItem;
import ro.gateway.aida.db.DBFilesPersMan;
import ro.gateway.aida.db.DBPersistenceManager;
import ro.gateway.aida.db.DBPersistenceToken;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.fnd.FndPersMan;
import ro.gateway.aida.fnd.FundingItem;
import ro.gateway.aida.obj.AIDAActivityObject;
import ro.gateway.aida.obj.AIDADocument;
import ro.gateway.aida.obj.AIDALocation;
import ro.gateway.aida.obj.AIDAObjSector;
import ro.gateway.aida.obj.AIDASector;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.obj.ActivityRelation;
import ro.gateway.aida.obj.ActivityStatus;
import ro.gateway.aida.obj.AidaResource;
import ro.gateway.aida.obj.CRegion;
import ro.gateway.aida.obj.Category;
import ro.gateway.aida.obj.ContactInfo;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.County;
import ro.gateway.aida.obj.GenericActivityProperty;
import ro.gateway.aida.obj.Organization;
import ro.gateway.aida.obj.OrganizationInv;
import ro.gateway.aida.obj.OrganizationRole;
import ro.gateway.aida.obj.Person;
import ro.gateway.aida.obj.PersonInv;
import ro.gateway.aida.obj.Region;
import ro.gateway.aida.obj.Town;
import ro.gateway.aida.obj.Village;
import ro.gateway.aida.obj.db.*;
import ro.gateway.aida.srv.IIDGenerator;
import ro.gateway.aida.struts.form.EditCategoryForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.LoginServlet;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserConstants;
import ro.gateway.aida.usr.messaging.AlertDispacher;
import ro.gateway.aida.usr.messaging.Event;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.Utils;
import ro.gateway.aida.autodates.StatusAutomation$Task;
import ro.xblue.translator.LanguageBean;
import ro.xblue.translator.TranslatorUtils;


/**
 * <p>Title: Romanian AIDA</p> <p>Description: </p> <p>Copyright: Copyright (comparator) 2003</p> <p>Company:
 * ro-gateway</p>
 *
 * @author Mihai Popoaei, mihai_popoaei@yahoo.com, smike@intellisource.ro
 * @version 1.0-* @version $Id: EditActivityServlet.java,v 1.2 2005/04/04 00:09:02 mihaipostelnicu Exp $
 */
public class EditActivityServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		request.setAttribute(SIGNATURE, SIGNATURE);

		HttpSession session = request.getSession();

		boolean firstTime = false;

		// generate new key or get the key from request
		String key = Utils.getValidTrimedString(request, PNAME_KEY, null);

		if (key == null) {
			firstTime = true;
			key = Utils.getHash(request.getSession().getId() +
				  System.currentTimeMillis());
			request.setAttribute(PNAME_FIRST_TIME, PNAME_FIRST_TIME);
			// System.err.println( "editare noua:" );
		}

		request.setAttribute(PNAME_KEY, key);

		// the editing contexts
		Hashtable ed_ctxs = (Hashtable) session.getAttribute(ED_CTXS);

		if (ed_ctxs == null) {
			ed_ctxs = new Hashtable();
			session.setAttribute(ED_CTXS, ed_ctxs);
		}

		// the editing context
		Hashtable ed_ctx = (Hashtable) ed_ctxs.get(key);

		if ((!firstTime) && (ed_ctx == null)) {
			// sesiune expirata | keye invalida
			System.err.println("Session Expired!");
			request.setAttribute(PNAME_ERRORS,
				  new String[]{"Session Expired!"});
			request.setAttribute(PNAME_SCREEN, SCREEN_ERROR);
			request.getRequestDispatcher(JSP_PAGE).forward(request, response);

			return;
		}

		if (ed_ctx == null) {
			ed_ctx = new Hashtable();
			ed_ctxs.put(key, ed_ctx);
		}

		request.setAttribute(PNAME_R_CTX, ed_ctx);

		String action = HttpUtils.getValidTrimedString(request, PNAME_ACTION,
			  null);

		if (ACTION_SAVE.equals(action)) {
			save(request, response);

			return;
		}

		response.setHeader("Expires", "0");
		response.setHeader("Pragma", "no-cache");

		String spage = Utils.getValidTrimedString(request, "page", null);
		if ("preview".equals(spage)) {
			Utils.setBreadCrumbs(request, "bc.project.page7");
			page_preview(request, response);
			return;
		}
		int page = Utils.getInt(request, "page", 1);

		if (firstTime) {
			page = 1;
		}

		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request, getServletContext());
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);
		if (bean != null) {
			bean.setView_lang(lang_bean.language);
		}
		switch (page) {
			case 1:
				Utils.setBreadCrumbs(request, "bc.project.page1");
				page1(request, response);

				break;

			case 2:
				Utils.setBreadCrumbs(request, "bc.project.page2");
				page2(request, response);

				break;

			case 3:
				Utils.setBreadCrumbs(request, "bc.project.page3");
				page3(request, response);

				break;

			case 4:
				Utils.setBreadCrumbs(request, "bc.project.page4");
				page4(request, response);

				break;

			case 5:
				Utils.setBreadCrumbs(request, "bc.project.page5");
				page5(request, response);

				break;

			case 6:
				Utils.setBreadCrumbs(request, "bc.project.page6");
				page6(request, response);

				break;

			case 7:
				Utils.setBreadCrumbs(request, "bc.project.page7");
				page7(request, response);

				break;
		}
	}

	private boolean isPage1Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_TITLE) &&
			  (bean.getTitle("ro") == null)) {
			h_errors.put("general_errors", "err.title_req");
		}

		if (aoo.isMandatory(ActObjsOptsConst.APPROVAL_DATE) &&
			  (bean.getDate_pa() == -1)) {
			h_errors.put(ActObjsOptsConst.APPROVAL_DATE, "err.aapproval_date");
		}

		if (aoo.isMandatory(ActObjsOptsConst.APPROVAL_DATE_REAL) &&
			  (bean.getDate_aa() == -1)) {
			h_errors.put(ActObjsOptsConst.APPROVAL_DATE_REAL,
				  "err.papproval_date");
		}

		if (aoo.isMandatory(ActObjsOptsConst.STARTING_DATE) &&
			  (bean.getDate_ps() == -1)) {
			h_errors.put(ActObjsOptsConst.STARTING_DATE, "err.pstart_date_req");
		}

		if (aoo.isMandatory(ActObjsOptsConst.STARTING_DATE_REAL) &&
			  (bean.getDate_as() == -1)) {
			h_errors.put(ActObjsOptsConst.STARTING_DATE_REAL,
				  "err.astart_date_req");
		}

		if (aoo.isMandatory(ActObjsOptsConst.CLOSING_DATE) &&
			  (bean.getDate_ps() == -1)) {
			h_errors.put(ActObjsOptsConst.CLOSING_DATE, "err.pclose_date_req");
		}

		if (aoo.isMandatory(ActObjsOptsConst.CLOSING_DATE_REAL) &&
			  (bean.getDate_as() == -1)) {
			h_errors.put(ActObjsOptsConst.CLOSING_DATE_REAL,
				  "err.aclose_date_req");
		}

		if (aoo.isMandatory(ActObjsOptsConst.STATUS) &&
			  ((bean.getStatus() == null) ||
			  (bean.getStatus().getId() == -1))) {
			h_errors.put(ActObjsOptsConst.STATUS, "err.status_req");
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);

			return false;
		}

		return true;
	}

	public void page1(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();
		Hashtable services = (Hashtable) application.getAttribute(Constants.SERVICES);
		String ctx_path = request.getContextPath();

		if (services == null) {
			System.err.println("services null... edit activity");

			return;
		}

		PersistenceToken token = PersistenceManager.tokenLookup(application);

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);
		boolean firstTime = null != request.getAttribute(PNAME_FIRST_TIME);
		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
			  application);

		User user = (User) session.getAttribute(UserConstants.LOGGED_USER);

		if (user == null) {
			String query = request.getQueryString();
			String referer = request.getContextPath() + "/editActivity?" +
				  ((query != null) ? query : "");

			session.invalidate();
			session = request.getSession(true);
			session.setAttribute(LoginServlet.PNAME_REFERER, referer);
			response.sendRedirect(request.getContextPath() + "/login.jsp");

			return;
		}

		String edtype = null;
		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);

		if (firstTime) {
			edtype = Utils.getValidTrimedString(request, PNAME_EDTYPE,
				  EDTYPE_NEW);
			ed_ctx.put(PNAME_EDTYPE, edtype);
			ed_ctx.put(PNAME_REFERER,
				  HttpUtils.getReferer(request, "", ctx_path + "/",
					    new String[]{"editActivity"}));
		} else {
			edtype = (String) ed_ctx.get(PNAME_EDTYPE);
		}

		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (bean == null) {
			// incepe o editare de activitate
			if (EDTYPE_EDIT.equals(edtype) || EDTYPE_DELETE.equals(edtype)) {
				long id = Utils.getLong(request, "id", -1);

				try {
					while (true) {
						if (id == -1) {
							break;
						}

						bean = ActivityDB.getManager(token).getAllDataById(id);

						if (bean == null) {
							break;
						}

						/**
						 * </pregatire_selectoare>
						 * Pregatesc pt. selectoare.
						 * pun in sesiune vectorii de organizatii si persoane
						 * pt. editarea listelor
						 */
						Hashtable orgs_beans = (Hashtable) session.getAttribute(OrgSelectorServlet.PNAME_BEANS);

						if (orgs_beans == null) {
							orgs_beans = new Hashtable();
							session.setAttribute(OrgSelectorServlet.PNAME_BEANS,
								  orgs_beans);
						}

						Hashtable orgs_bean = (Hashtable) orgs_beans.get(OrgSelectorServlet.PNAME_ORGSELS);

						if (orgs_bean == null) {
							orgs_bean = new Hashtable();
							orgs_beans.put(OrgSelectorServlet.PNAME_ORGSELS,
								  orgs_bean);
						}

						orgs_bean.put("donor" + key,
							  OrganizationInv.buildOrgInvVector(bean.getOrgsByLRId(OrganizationRole.DONOR_ORG_ROLE)));
						orgs_bean.put("con" + key,
							  OrganizationInv.buildOrgInvVector(bean.getOrgsByLRId(OrganizationRole.CONTRACTING_ORG_ROLE)));
						orgs_bean.put("ben" + key,
							  OrganizationInv.buildOrgInvVector(bean.getOrgsByLRId(OrganizationRole.BENEFICIARS_ORG_ROLE)));

						// persoane
						Hashtable pers_beans = (Hashtable) session.getAttribute(PersSelectorServlet.PNAME_BEANS);

						if (pers_beans == null) {
							pers_beans = new Hashtable();
							session.setAttribute(PersSelectorServlet.PNAME_BEANS,
								  pers_beans);
						}

						Hashtable pers_bean = (Hashtable) pers_beans.get(PersSelectorServlet.PNAME_PERSELS);

						if (pers_bean == null) {
							pers_bean = new Hashtable();
							pers_beans.put(PersSelectorServlet.PNAME_PERSELS,
								  pers_bean);
						}

						pers_bean.put("con" + key,
							  PersonInv.buildPersInvVector(bean.getPersonsByLRId(OrganizationRole.CONTRACTING_ORG_ROLE)));
						pers_bean.put("fin" + key,
							  PersonInv.buildPersInvVector(bean.getPersonsByLRId(OrganizationRole.FINANCING_ORG_ROLE)));
						pers_bean.put("ben" + key,
							  PersonInv.buildPersInvVector(bean.getPersonsByLRId(OrganizationRole.BENEFICIARS_ORG_ROLE)));
						pers_bean.put("oth" + key,
							  PersonInv.buildPersInvVector(bean.getPersonsByLRId(OrganizationRole.NO_ROLE)));

						// proiecte
						Hashtable prj_beans = (Hashtable) session.getAttribute(ActivitySelectorServlet.PNAME_BEANS);

						if (prj_beans == null) {
							prj_beans = new Hashtable();
							session.setAttribute(ActivitySelectorServlet.PNAME_BEANS,
								  prj_beans);
						}

						Hashtable prj_bean = (Hashtable) ((prj_beans == null)
							  ? null
							  : prj_beans.get(ActivitySelectorServlet.PNAME_ACTSELS));

						if (prj_bean == null) {
							prj_bean = new Hashtable();
							prj_beans.put(ActivitySelectorServlet.PNAME_ACTSELS,
								  prj_bean);
						}

						ActivityRelation[] rels = bean.getAct_relationsArray();

						if (rels == null) {
							rels = new ActivityRelation[0];
						}

						Vector v_proj = new Vector();
						prj_bean.put("relbox" + key, v_proj);

						for (int i = 0; i < rels.length; i++) {
							ActivityRelation rel = rels[i];
							v_proj.add(rel.getRelToTitle());
						}

						// for orgType selector
						ArrayList cats = bean.getCategories();
						HashSet catsel = new HashSet();

						for (int i = 0; i < cats.size(); i++) {
							Category cat = (Category) cats.get(i);
							catsel.add(cat);
						}

						session.setAttribute("catlist", catsel);

						/**
						 * </pregatire_selectoare>
						 */
						break;
					}

					if (bean != null) {
						ed_ctx.put(PNAME_BEAN, bean);
					}
				} catch (SQLException sqlEx) {
					sqlEx.printStackTrace();
				}

				if ((id == -1) || (bean == null)) {
					Hashtable ed_ctxs = (Hashtable) session.getAttribute(ED_CTXS);
					ed_ctxs.remove(key);

					request.setAttribute(PNAME_ERRORS,
						  new String[]{"Activity not found"});
					request.setAttribute(PNAME_SCREEN, SCREEN_ERROR);
					request.getRequestDispatcher(JSP_PAGE).forward(request,
						  response);

					return;
				}

				// no id ???
			} else if (EDTYPE_NEW.equals(edtype)) {
				// activitate noua
				bean = new Activity();
				try {
					bean.setStatus_automation_on("true".equals(SystemPropertyDB.getManager(token).getProperty("statusautomation")));
				} catch (SQLException e) {
					e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
				}
				ed_ctx.put(PNAME_BEAN, bean);
			}

			AIDAActivityObject object = bean.getObject();

			if (object == null) {
				object = new AIDAActivityObject();
				object.setUser_id(user.getId());
				bean.setObject(object);

				// ARE DREPTURI SA CREEZE Activity?
			} else {
				// ARE DREPTURI SA EDITEZE Activity?
				Arbiter ar = Arbiter.getManager(token);

				if (!ar.canDo(request, Perms.EDIT_OBJECT, bean.getId(),
					  Arbiter.PROJECT_TYPE))
				//if ( !ro.gateway.aida.obj.ActivityUtils.canEdit( user, bean ) )
				{
					ed_ctx.remove(PNAME_BEAN);

					request.setAttribute(PNAME_ERRORS,
						  new String[]{"Access denied."});
					request.setAttribute(PNAME_SCREEN, SCREEN_ERROR);
					request.getRequestDispatcher(JSP_PAGE).forward(request,
						  response);

					return;
				}
			}

			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE1).forward(request, response);

			return;
		}

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE1).forward(request, response);

			return;
		}

		if ("remove_donors".equals(action)) {
			String[] donor_ids = request.getParameterValues("selected_donor");
			removeOrganizations(bean, donor_ids, session, key,
				  OrganizationRole.DONOR_ORG_ROLE);
			response.sendRedirect("editActivity?page=1&key=" + key);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			bean.setTransfrontalier("yes".equals(Utils.getValidTrimedString(request, "is_tf", "no")));

			bean.setTitle(lang_bean.language,
				  Utils.getValidTrimedString(request, "title", null));

			int z_ap = Utils.getInt(request, "z_ap", -1);
			int l_ap = Utils.getInt(request, "l_ap", -1);
			int a_ap = Utils.getInt(request, "a_ap", -1);

			int z_sp = Utils.getInt(request, "z_sp", -1);
			int l_sp = Utils.getInt(request, "l_sp", -1);
			int a_sp = Utils.getInt(request, "a_sp", -1);

			int z_ep = Utils.getInt(request, "z_ep", -1);
			int l_ep = Utils.getInt(request, "l_ep", -1);
			int a_ep = Utils.getInt(request, "a_ep", -1);

			int z_aa = Utils.getInt(request, "z_aa", -1);
			int l_aa = Utils.getInt(request, "l_aa", -1);
			int a_aa = Utils.getInt(request, "a_aa", -1);

			int z_sa = Utils.getInt(request, "z_sa", -1);
			int l_sa = Utils.getInt(request, "l_sa", -1);
			int a_sa = Utils.getInt(request, "a_sa", -1);

			int z_ea = Utils.getInt(request, "z_ea", -1);
			int l_ea = Utils.getInt(request, "l_ea", -1);
			int a_ea = Utils.getInt(request, "a_ea", -1);

			Calendar cal = Calendar.getInstance();

			if ((z_ap != -1) && (l_ap != -1) && (a_ap != -1)) {
				cal.set(a_ap, l_ap, z_ap, 0, 0, 0);
				bean.setDate_pa(cal.getTimeInMillis());
			} else {
				bean.setDate_pa(-1);
			}

			if ((z_sp != -1) && (l_sp != -1) && (a_sp != -1)) {
				cal.set(a_sp, l_sp, z_sp, 0, 0, 0);
				bean.setDate_ps(cal.getTimeInMillis());
			} else {
				bean.setDate_ps(-1);
			}

			if ((z_ep != -1) && (l_ep != -1) && (a_ep != -1)) {
				cal.set(a_ep, l_ep, z_ep, 0, 0, 0);
				bean.setDate_pe(cal.getTimeInMillis());
			} else {
				bean.setDate_pe(-1);
			}

			String same_aa = Utils.getValidTrimedString(request, "same_aa", null);

			if (same_aa != null) {
				bean.setDate_aa(bean.getDate_pa());
			} else {
				if ((z_aa != -1) && (l_aa != -1) && (a_aa != -1)) {
					cal.set(a_aa, l_aa, z_aa, 0, 0, 0);
					bean.setDate_aa(cal.getTimeInMillis());
				} else {
					bean.setDate_aa(-1);
				}
			}

			String same_sa = Utils.getValidTrimedString(request, "same_sa", null);

			if (same_sa != null) {
				bean.setDate_as(bean.getDate_ps());
			} else {
				if ((z_sa != -1) && (l_sa != -1) && (a_sa != -1)) {
					cal.set(a_sa, l_sa, z_sa, 0, 0, 0);
					bean.setDate_as(cal.getTimeInMillis());
				} else {
					bean.setDate_as(-1);
				}
			}

			String same_ea = Utils.getValidTrimedString(request, "same_ea", null);

			if (same_ea != null) {
				bean.setDate_ae(bean.getDate_pe());
			} else {
				if ((z_ea != -1) && (l_ea != -1) && (a_ea != -1)) {
					cal.set(a_ea, l_ea, z_ea, 0, 0, 0);
					bean.setDate_ae(cal.getTimeInMillis());
				} else {
					bean.setDate_ae(-1);
				}
			}

			String extins = Utils.getValidTrimedString(request, "extins", null);

			if ("da".equals(extins)) {
				int z_ext = Utils.getInt(request, "z_ext", -1);
				int l_ext = Utils.getInt(request, "l_ext", -1);
				int a_ext = Utils.getInt(request, "a_ext", -1);

				if ((z_ext != -1) && (l_ext != -1) && (a_ext != -1)) {
					cal.set(a_ext, l_ext, z_ext, 0, 0, 0);
					bean.setDate_ext(cal.getTimeInMillis());
				} else {
					bean.setDate_ext(System.currentTimeMillis());
				}
			} else {
				bean.setDate_ext(-1);
			}
			String text = Utils.getValidTrimedString(request, "ext_text",
				  null);
			bean.setExtensionReason(lang_bean.language, text);

			ActivityStatus status = bean.getStatus();

			if (status == null) {
				status = new ActivityStatus();
				bean.setStatus(status);
			}

			bean.setStatus_automation_on(HttpUtils
				  .getValidTrimedString(request, "autostatus", "false").equals("true"));
			if (!bean.isStatus_automation_on()) {
				long status_id = HttpUtils.getLong(request, "status", -1);
				if (status_id == -2) {
					String status_str = HttpUtils.getValidTrimedString(request,
						  "st_custom", null);

					if (status_str != null) {
						if (status.getSt_code() != -1) {
							status.setSt_code(-1);
							status.setId(-1);
							status.clearDescriptions();
							status.clearStatuses();
						}

						status.setStatus(lang_bean.language, status_str);
//                         System.out.println( "new status:" + status_str );
					}
				} else {
					try {
						ActivityStatus st = ActivityStatusDB.getManager(token)
							  .getById(status_id);
						bean.setStatus(st);
					} catch (SQLException sqlEx) {
						sqlEx.printStackTrace();
						bean.setStatus(null);
					}
				}
			} else {
				bean.setStatus(StatusAutomation$Task.getStatusByDates(bean, token));
			}

//                  if ( ( status_id == 4 ) || ( status_id == 5 ) )
//                  {
			bean.setStatusReason(lang_bean.language,
				  HttpUtils.getValidTrimedString(request, "status_reason",
					    null));
//                  }
//                  else
//                  {
//                        bean.clearStatusReasons();
//                  }

			// DONOR STUFF
			String[] paraNames = HttpUtils.getParametersLike(request,
				  "donor_prj_id");

			if (paraNames != null) {
				for (int i = 0; i < paraNames.length; i++) {
					String donor_prj_id = HttpUtils.getValidTrimedString(request,
						  paraNames[i], null);
					long donor_id = -1;

					try {
						donor_id = Long.parseLong(paraNames[i].substring(12));
					} catch (Exception ex) {
					}

					if (donor_prj_id == null) {
						bean.removeDonorPrjId(donor_id);
					} else {
						bean.setDonorIdForOrg(donor_id, donor_prj_id);
					}
				}
			}

			String after_selector = HttpUtils.getValidTrimedString(request,
				  "after_selector", null);

			if (after_selector != null) {
				if ("orgs".equals(after_selector)) {
					ArrayList v_orgs = (ArrayList) session.getAttribute("SelectedOrgs");
					session.removeAttribute("SelectedOrgs");

					/*  List orgs_beans = ( List ) session.getAttribute("SelectedOrgs" );
					  Hashtable orgs_bean = ( Hashtable ) ( ( orgs_beans == null )
						   ? null : orgs_beans.get( OrgSelectorServlet.PNAME_ORGSELS ) );
					  Vector v_orgs = ( Vector ) ( ( orgs_bean == null ) ? null
						   : orgs_bean.get(
							    "donor" + key ) );
					*/
					if (v_orgs != null) {
						OrganizationInv[] orgs = OrganizationInv.buildOrgInvArray(v_orgs,
							  OrganizationRole.DONOR_ORG_ROLE);

						if (orgs != null) {
							//   bean.removeOrgsByLRoleId( OrganizationRole.DONOR_ORG_ROLE );
							bean.addOrgs(orgs, OrganizationRole.DONOR_ORG_ROLE);
						}

						//else
						//    bean.removeOrgsByLRoleId( OrganizationRole.DONOR_ORG_ROLE );
					}

					//else
					//    bean.removeOrgsByLRoleId( OrganizationRole.DONOR_ORG_ROLE );
					// validare project_id deja introduse
				}

				// if orgs == after_selector
				response.sendRedirect("editActivity?page=1&key=" + key);

				return;
			}

			String more_donor_ids = Utils.getValidTrimedString(request,
				  "f_more_ids", null);

			if (more_donor_ids != null) {
				response.sendRedirect("editActivity?page=1&key=" + key);

				return;
			}

			if (!isPage1Valid(ed_ctx, bean)) {
				response.sendRedirect("editActivity?page=1&key=" + key);

				return;
			}

			String preview_data = Utils.getValidTrimedString(request,
				  "preview_data", null);

			if ("true".equals(preview_data)) {
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			response.sendRedirect("editActivity?page=2&key=" + key);

			return;
		}
	}

	private boolean isPage2Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.LOCATIONS)) {
			AIDALocation[] locations = bean.getLocations();

			if ((locations == null) || (locations.length < 1)) {
				h_errors.put(ActObjsOptsConst.LOCATIONS, "err.location_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.SECTORS)) {
			AIDAObjSector[] sectors = bean.getSectors();

			if ((sectors == null) || (sectors.length < 1)) {
				h_errors.put(ActObjsOptsConst.SECTORS, "err.sector_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CATEGORIES)) {
			Category[] categories = bean.getCategoriesArray();

			if ((categories == null) || (categories.length < 1)) {
				h_errors.put(ActObjsOptsConst.PROJECT_CATEGORIES, "err.cats_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.COMPONENTS)) {
			GenericActivityProperty[] components = bean.getComponents();

			if ((components == null) || (components.length < 1)) {
				h_errors.put(ActObjsOptsConst.COMPONENTS, "err.components_req");
			}
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);
//               System.out.println( "return page2 validation: false" );

			return false;
		}

//          System.out.println( "return page2 validation: true" );

		return true;
	}

	public void page2(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();
		Hashtable services = (Hashtable) application.getAttribute(Constants.SERVICES);
		PersistenceToken token = PersistenceManager.tokenLookup(application);

		if (services == null) {
			System.err.println("services null... edit activity");

			return;
		}

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
			  application);

//          System.out.println( "\t\taction:" + action );

		// add location
		if ("add_loc".equals(action)) {
			// add location
			int rid = Utils.getInt(request, "rid", -1);
			int jid = Utils.getInt(request, "jid", -1);
			int oid = Utils.getInt(request, "oid", -1);
			int lid = Utils.getInt(request, "lid", -1);
			String country_iso3 = Utils.getValidTrimedString(request, "country", null);
			int cregion_id = Utils.getInt(request, "cregion", -1);
//               System.out.println( "cregionid:" + cregion_id );

			AIDALocation location = new AIDALocation();
			try {
				while (true) {
					if (lid != -1) {
						Village loc = VillageDB.getManager(token).getById(lid);
						location.setLocalitate(loc);
						if (loc != null && loc.getSirsup_id() != -1) {
							oid = loc.getSirsup_id();
						} else {
							location = null;
							break;
						}
					}
					if (oid != -1) {
						Town town = TownDB.getManager(token).getById(oid);
						location.setOras(town);
						if (town != null && town.getJudet_id() != -1) {
							jid = town.getJudet_id();
						} else {
							location = null;
							break;
						}
					}
					if (jid != -1) {
						County county = CountyDB.getManager(token).getById(jid);
						location.setJudet(county);
						if (county != null && county.getRegiune_id() != -1) {
							rid = county.getRegiune_id();
						} else {
							location = null;
							break;
						}
					}
					if (rid != -1) {
						Region region = RegionDB.getManager(token).getById(rid);
						location.setRegion(region);
						if (region != null && region.getCountryIso3() != null) {
							country_iso3 = region.getCountryIso3();
						} else {
							location = null;
							break;
						}
					}
					if (country_iso3 != null) {
						Country country = AIDALocationDB.getManager(token).getCountryByISO3(country_iso3);
						location.setCountry(country);
						if (country != null && country.getCregion_id() != -1) {
							cregion_id = country.getCregion_id();
						} else {
							location = null;
							break;
						}
					}
					if (cregion_id != -1) {
						CRegion cregion = AIDALocationDB.getManager(token).getCRegionById(cregion_id);
//                              System.out.println( "cregion:" + cregion );
						location.setCregion(cregion);
						if (cregion == null) {
							location = null;
							break;
						}
					}
					break;
				}
			} catch (SQLException sqlEx) {
				sqlEx.printStackTrace();
			}

			if (location != null) {
//                    System.out.println( "cregion:" + location.getCregion().getName() );
				bean.addLocation(location);
			}
			response.sendRedirect("editActivity?page=2&key=" + key + "&#aloc");

			return;
		}

		if ("del_loc".equals(action)) {
			String[] values = request.getParameterValues("location_id");

			if (values != null) {
				java.util.Arrays.sort(values);

				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;

					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						bean.removeLocation(value);
					}
				}
			}

			response.sendRedirect("editActivity?page=2&key=" + key + "&#aloc");

			return;
		}

//          if ( "add_country".equals( action ) ) {
//               String country = Utils.getValidTrimedString( request, "country", null );
//               location = null;
//
//               if ( country != null ) {
//                    try {
//                         location = AIDALocationDB.getManager( token )
//                            .getCountryLocationByISO3( country );
//                    } catch ( SQLException e ) {
//                         e.printStackTrace(); //To change body of catch statement use Options | File Templates.
//                    }
//               }
//
//               if ( location != null ) {
//                    bean.addLocation( location );
//               }
//
//               response.sendRedirect( "editActivity?page=2&key=" + key );
//
//               return;
//          }

		if ("del_countries".equals(action)) {
			String[] values = request.getParameterValues("country_index");

			if (values != null) {
				java.util.Arrays.sort(values);

				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;

					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						bean.removeLocation(value);
					}
				}
			}

			response.sendRedirect("editActivity?page=2&key=" + key);

			return;
		}

		if ("add_sec".equals(action)) {
			int s_id = Utils.getInt(request, "s_id", -1);
			int ss_id = Utils.getInt(request, "ss_id", -1);
			int sss_id = Utils.getInt(request, "sss_id", -1);

			AIDASector subsector = null;
			AIDASector subsector1 = null;
			AIDASector sector = null;

			if (s_id != -1) {
				try {
					sector = AIDASectorPersMan.getManager(token).getById(s_id);
				} catch (SQLException sqlEx) {
					sqlEx.printStackTrace();
				}
			}

			if (ss_id != -1) {
				try {
					subsector = AIDASectorPersMan.getManager(token).getById(ss_id);
				} catch (SQLException sqlEx) {
					sqlEx.printStackTrace();
				}
			}

			if (sss_id != -1) {
				try {
					subsector1 = AIDASectorPersMan.getManager(token).getById(sss_id);
				} catch (SQLException sqlEx) {
					sqlEx.printStackTrace();
				}
			}

			if (sector != null) {
				AIDAObjSector objSector = new AIDAObjSector();
				objSector.setSector(sector);

				if (subsector != null) {
					objSector.setSubsector(subsector);
				}
				if (subsector1 != null) {
					objSector.setSubsector1(subsector1);
				}

				bean.addSector(objSector);
			}

			response.sendRedirect("editActivity?page=2&key=" + key +
				  "&#asector");

			return;
		}

		if ("del_sec".equals(action)) {
			String[] values = request.getParameterValues("sec_index");

			if (values != null) {
				java.util.Arrays.sort(values);

				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;

					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						bean.removeSector(value);
					}
				}
			}

			response.sendRedirect("editActivity?page=2&key=" + key +
				  "&#asector");

			return;
		}

		if (ACTION_EDIT.equals(action)) {
			if ("true".equals(request.getParameter("jts"))) {
				request.setAttribute(PNAME_SHUST_1, PV_SHUST_1_SECTOR);
			}

			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE2).forward(request, response);

			return;
		}

		if ("add_comp".equals(action)) {
			String comp_name = HttpUtils.getValidTrimedString(request,
				  "comp_name", null);

			if (comp_name != null) {
				GenericActivityProperty comp = new GenericActivityProperty(GenericActivityProperty.TYPE_COMPONENT);
				comp.setName(lang_bean.language, comp_name);

				bean.addComponent(comp);
			}

			response.sendRedirect("editActivity?key=" + key +
				  "&page=2&#acomps");

			return;
		}

		if ("del_comps".equals(action)) {
			String[] values = request.getParameterValues("comp_id");

			if (values != null) {
				java.util.Arrays.sort(values);

				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;

					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						bean.removeComponent(value);
					}
				}
			}

			response.sendRedirect("editActivity?key=" + key +
				  "&page=2&#acomps");

			return;
		}

		if ("cats_modified".equals(action)) {
			HashSet cat_list = (HashSet) session.getAttribute("catlist");
			ArrayList items = bean.getCategories();
			items.clear();

			if ((cat_list != null) && (cat_list.size() > 0)) {
				Iterator it = cat_list.iterator();

				while (it.hasNext()) {
					Object item = it.next();

					if (item instanceof Category) {
						items.add(item);
					} else if (item instanceof EditCategoryForm) {
						// wtf this is wrong... I should get Category here
						System.err.println("wrong checkpoint: " +
							  "bean should be Category... I get EditCategoryForm");

						try {
							Category cat = CategoryDB.getManager(token).get(((EditCategoryForm) item).getId());
							items.add(cat);
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}

			response.sendRedirect("editActivity?key=" + key + "&page=2&#acats");

			return;
		} else if ("del_cat".equals(action)) {
			String[] values = request.getParameterValues("cat_index");
			ArrayList items = bean.getCategories();

			if (values != null) {
				java.util.Arrays.sort(values);

				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;

					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						items.remove(value);
					}
				}
			}

			// for orgType selector
			HashSet catsel = new HashSet();

			for (int i = 0; i < items.size(); i++) {
				Category cat = (Category) items.get(i);
				catsel.add(cat);
			}

			session.setAttribute("catlist", catsel);

			response.sendRedirect("editActivity?page=2&key=" + key + "&#acat");

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			bean.setInternational("yes".equals(Utils.getValidTrimedString(request, "is_in", "no")));

			String clear_old_locations = Utils.getValidTrimedString(request,
				  "clear_old_locations", null);

			if (null != clear_old_locations) {
				if ("clear".equals(clear_old_locations)) {
					bean.removeAllLocations();
				} else {
				}

				response.sendRedirect("editActivity?page=2&key=" + key);

				return;
			}

			int nr_comps = HttpUtils.getInt(request, "nr_comps", 0);
			GenericActivityProperty[] comps = bean.getComponents();

			for (int i = 0; i < nr_comps; i++) {
				String name = HttpUtils.getValidTrimedString(request,
					  "compname" + i, null);
				comps[i].setName(lang_bean.language, name);
			}

			if (!isPage2Valid(ed_ctx, bean)) {
				response.sendRedirect("editActivity?page=2&key=" + key);

				return;
			}

			String preview_data = Utils.getValidTrimedString(request,
				  "preview_data", null);

			if ("true".equals(preview_data)) {
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			response.sendRedirect("editActivity?page=3&key=" + key);

			return;
		}
	}

	private boolean isPage3Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.FUNDING_ORGS)) {
			OrganizationInv[] orgs = bean.getOrgsByLRId(OrganizationRole.FINANCING_ORG_ROLE);

			if ((orgs == null) || (orgs.length < 1)) {
				h_errors.put(ActObjsOptsConst.FUNDING_ORGS, "err.forgs_req");
			}
		}

		//            if ( aoo.isMandatory( ActObjsOptsConst.FUNDING_PERSONS ) )
		//            {
		//                  PersonInv[] pers = bean.
		//                        getPersonsByLRId( OrganizationRole.FINANCING_ORG_ROLE );
		//                  if ( ( pers == null ) || ( pers.length < 1 ) )
		//                  {
		//                        h_errors.put( ActObjsOptsConst.FUNDING_PERSONS, "err.fpers_req" );
		//                  }
		//            }
		if (aoo.isMandatory(ActObjsOptsConst.FUNDING_ITEMS)) {
			FundingItem[] items = bean.getFunding_itemsArray();

			if ((items == null) || (items.length < 1)) {
				h_errors.put(ActObjsOptsConst.FUNDING_ITEMS, "err.fitems_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.ACT_RELATIONS)) {
			ActivityRelation[] rels = bean.getAct_relationsArray();

			if ((rels == null) || (rels.length < 1)) {
				h_errors.put(ActObjsOptsConst.ACT_RELATIONS, "err.actrels_req");
			}
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);

			return false;
		}

		return true;
	}

	public void page3(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();
		Hashtable services = (Hashtable) application.getAttribute(Constants.SERVICES);

		if (services == null) {
			System.err.println("services null... edit activity");

			return;
		}

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE3).forward(request, response);

			return;
		}


		if ("remove_fin_orgs".equals(action)) {
			String[] fin_orgs_ids = request.getParameterValues("selected_forg");
			removeOrganizations(bean, fin_orgs_ids, session, key,
				  OrganizationRole.FINANCING_ORG_ROLE);
			response.sendRedirect("editActivity?page=3&key=" + key);

			return;
		} else if ("remove_fin_pers".equals(action)) {
			String[] fin_pers_ids = request.getParameterValues("finpers_id");
			removePersons(bean, fin_pers_ids, session, key,
				  OrganizationRole.FINANCING_ORG_ROLE);
			response.sendRedirect("editActivity?page=3&key=" + key);

			return;
		} else if ("remove_relations".equals(action)) {
			String[] prj_ids = request.getParameterValues("rprj_id");

			if (prj_ids != null) {
				for (int i = 0; i < prj_ids.length; i++) {
					long id_ = -1;
					try {
						id_ = Long.parseLong(prj_ids[i]);
					} catch (Exception ex) {
					}
					if (id_ == -1) continue;

					ArrayList relations = bean.getAct_relations();
					for (int j = 0; j < relations.size(); j++) {
						ActivityRelation rel = (ActivityRelation) relations.get(j);
						if (rel.getRelto_activity_id() == id_) {
							relations.remove(j);
							j--;
						}
					}
				}
			}

			response.sendRedirect("editActivity?page=3&key=" + key);

			return;
		} else if ("remove_fin_items".equals(action)) {
			while (true) {
				long forg_id = HttpUtils.getLong(request, "forg_id", -1);

				if (forg_id == -1) {
					break;
				}

				int fitem_idx = HttpUtils.getInt(request, "fitem_idx", -1);

				if (fitem_idx == -1) {
					break;
				}

				ArrayList items = bean.getFndItemsForOrg(forg_id);

				if (items == null) {
					break;
				}

				if ((fitem_idx < 0) || (fitem_idx >= items.size())) {
					break;
				}

				items.remove(fitem_idx);

				break;
			}

			response.sendRedirect("editActivity?page=3&key=" + key);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			ArrayList relations = bean.getAct_relations();

			for (int i = 0; i < relations.size(); i++) {
				ActivityRelation rel = (ActivityRelation) relations.get(i);
				rel.setRelation(HttpUtils.getValidTrimedString(request,
					  "relation" + rel.getRelto_activity_id(), null));

				if ((rel.getRelation() == null) ||
					  (rel.getRelation().length() < 1)) {
					relations.remove(i);
					i--;

					continue;
				}

//                    System.out.println( "insert:rel:" + rel.getActivity_id() + "- " +
//                       rel.getRelation() + "->" + rel.getRelto_activity_id() );
			}

			// ma uit dupa persoane si organizatii
			// daca gasesc raman pe pagina asta
			String after_selector = HttpUtils.getValidTrimedString(request,
				  "after_selector", null);

			if (after_selector != null) {
				if ("orgs".equals(after_selector)) {
					ArrayList v_orgs = (ArrayList) session.getAttribute("SelectedOrgs");
					session.removeAttribute("SelectedOrgs");

					/*  Hashtable orgs_beans = ( Hashtable ) session.getAttribute( OrgSelectorServlet.PNAME_BEANS );
					  Hashtable orgs_bean = ( Hashtable ) ( ( orgs_beans == null )
						   ? null : orgs_beans.get( OrgSelectorServlet.PNAME_ORGSELS ) );
					  Vector v_orgs = ( Vector ) ( ( orgs_bean == null ) ? null
						   : orgs_bean.get(
							    "fin" + key ) );

					  if ( v_orgs != null )
					  {
						   orgs_bean.remove( "fin" + key );
					  }
					  */
					if (v_orgs != null) {
						OrganizationInv[] orgs = OrganizationInv.buildOrgInvArray(v_orgs,
							  OrganizationRole.FINANCING_ORG_ROLE);

						if (orgs != null) {
							bean.addOrgs(orgs,
								  OrganizationRole.FINANCING_ORG_ROLE);
						}
					}
				} else if ("pers".equals(after_selector)) {
					Person v_person = (Person) session.getAttribute(Person.SELECTED);

					if (v_person != null) {
						PersonInv pi = new PersonInv(v_person,
							  OrganizationRole.getCachedByLocalId(OrganizationRole.FINANCING_ORG_ROLE));
						bean.getPersons_involved().add(pi);
					}

					session.removeAttribute(Person.SELECTED);
				} else if ("proiect".equals(after_selector)) {
//                         System.out.println( "after_project_sel" );

					ActivityRelation ar = (ActivityRelation) session.getAttribute(ActivityRelation.SELECTED);
					if (ar != null) {
						bean.getAct_relations().add(ar);
					} else {
						bean.getAct_relations().clear();
						// sterge relatiile existente
					}
				}

				response.sendRedirect("editActivity?page=3&key=" + key);

				return;
			}

			//                  else if ( after_funding != null )
			//                  {
			//                        response.sendRedirect( "editActivity?page=3&key=" + key +
			//                              "&#afitems" );
			//                        return;
			//                  }
			//                  else if ( delfitems != null )
			//                  {
			//                        String[] values = request.getParameterValues( "fitem_idx" );
			//
			//                        if ( values != null )
			//                        {
			//                              java.util.Arrays.sort( values );
			//
			//                              for ( int i = values.length - 1; i >= 0; i-- )
			//                              {
			//                                    int value = -1;
			//
			//                                    try
			//                                    {
			//                                          value = Integer.parseInt( values[ i ] );
			//                                    }
			//                                    catch ( NumberFormatException nfEx )
			//                                    {
			//                                    }
			//
			//                                    if ( value != -1 )
			//                                          bean.getFunding_items().remove( value );
			//                              }
			//                        }
			//
			//                        response.sendRedirect( "editActivity?page=3&key=" + key +
			//                              "&#afitems" );
			//                        return;
			//                  }
			if (!isPage3Valid(ed_ctx, bean)) {
				response.sendRedirect("editActivity?page=3&key=" + key);

				return;
			}

			String preview_data = Utils.getValidTrimedString(request,
				  "preview_data", null);

			if ("true".equals(preview_data)) {
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			// nu a selectat orgs sau pers, asa ca trec la urmatoarea pagina
			response.sendRedirect("editActivity?page=4&key=" + key);

			return;
		}
	}

	private boolean isPage4Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.CONTRACTING_ORGS)) {
			OrganizationInv[] orgs = bean.getOrgsByLRId(OrganizationRole.CONTRACTING_ORG_ROLE);

			if ((orgs == null) || (orgs.length < 1)) {
				h_errors.put(ActObjsOptsConst.CONTRACTING_ORGS,
					  "err.contr_orgs_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.CONTRACTING_PERS)) {
			PersonInv[] pers = bean.getPersonsByLRId(OrganizationRole.CONTRACTING_ORG_ROLE);

			if ((pers == null) || (pers.length < 1)) {
				h_errors.put(ActObjsOptsConst.CONTRACTING_PERS,
					  "err.contr_pers_req");
			}
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);

			return false;
		}

		return true;
	}

	public void page4(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();
		Hashtable services = (Hashtable) application.getAttribute(Constants.SERVICES);

		if (services == null) {
			System.err.println("services null... edit activity");

			return;
		}

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE4).forward(request, response);

			return;
		}

		if ("remove_contr_orgs".equals(action)) {
			String[] contr_orgs_ids = request.getParameterValues("conorg_id");
			removeOrganizations(bean, contr_orgs_ids, session, key,
				  OrganizationRole.CONTRACTING_ORG_ROLE);
			response.sendRedirect("editActivity?page=4&key=" + key);

			return;
		}

		if ("remove_contr_pers".equals(action)) {
			String[] contr_pers_ids = request.getParameterValues("conpers_id");
			removePersons(bean, contr_pers_ids, session, key,
				  OrganizationRole.CONTRACTING_ORG_ROLE);
			response.sendRedirect("editActivity?page=4&key=" + key);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			// ma uit dupa persoane si organizatii
			// daca gasesc raman pe pagina asta
			String after_selector = HttpUtils.getValidTrimedString(request,
				  "after_selector", null);

			if (after_selector != null) {
				if ("orgs".equals(after_selector)) {
					ArrayList v_orgs = (ArrayList) session.getAttribute("SelectedOrgs");
					session.removeAttribute("SelectedOrgs");

					/*  Hashtable orgs_beans = ( Hashtable ) session.getAttribute( OrgSelectorServlet.PNAME_BEANS );
					  Hashtable orgs_bean = ( Hashtable ) ( ( orgs_beans == null )
						   ? null : orgs_beans.get( OrgSelectorServlet.PNAME_ORGSELS ) );
					  Vector v_orgs = ( Vector ) ( ( orgs_bean == null ) ? null
						   : orgs_bean.get(
							    "con" + key ) );
					*/
					if (v_orgs != null) {
						OrganizationInv[] orgs = OrganizationInv.buildOrgInvArray(v_orgs,
							  OrganizationRole.CONTRACTING_ORG_ROLE);

						if (orgs != null) {
							bean.addOrgs(orgs,
								  OrganizationRole.CONTRACTING_ORG_ROLE);
						}
					}
				} else if ("pers".equals(after_selector)) {
					Person v_person = (Person) session.getAttribute(Person.SELECTED);

					if (v_person != null) {
						PersonInv pi = new PersonInv(v_person,
							  OrganizationRole.getCachedByLocalId(OrganizationRole.CONTRACTING_ORG_ROLE));
						bean.getPersons_involved().add(pi);
					}

					session.removeAttribute(Person.SELECTED);
				}

				response.sendRedirect("editActivity?page=4&key=" + key);

				return;
			}

			if (!isPage4Valid(ed_ctx, bean)) {
				// nu a selectat orgs sau pers, asa ca trec la urmatoarea pagina
				response.sendRedirect("editActivity?page=4&key=" + key);

				return;
			}

			String preview_data = Utils.getValidTrimedString(request,
				  "preview_data", null);

			if ("true".equals(preview_data)) {
				//                request.setAttribute( PNAME_SCREEN, SCREEN_CONFIRM );
				//                request.getRequestDispatcher( JSP_PAGE ).forward( request, response );
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			response.sendRedirect("editActivity?page=5&key=" + key);

			return;
		}
	}

	private boolean isPage5Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.BENEF_ORGS)) {
			OrganizationInv[] orgs = bean.getOrgsByLRId(OrganizationRole.BENEFICIARS_ORG_ROLE);

			if ((orgs == null) || (orgs.length < 1)) {
				h_errors.put(ActObjsOptsConst.BENEF_ORGS, "err.benorgs_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.BENEF_PERS)) {
			PersonInv[] pers = bean.getPersonsByLRId(OrganizationRole.BENEFICIARS_ORG_ROLE);

			if ((pers == null) || (pers.length < 1)) {
				h_errors.put(ActObjsOptsConst.BENEF_PERS, "err.benpers_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.DESCRIPTION)) {
			if (bean.getDescription("ro") == null) {
				h_errors.put(ActObjsOptsConst.DESCRIPTION, "err.descr_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PRIMARY_OBJECTIVE)) {
			if (bean.getObjective("ro") == null) {
				h_errors.put(ActObjsOptsConst.PRIMARY_OBJECTIVE,
					  "err.primobj_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.RES_PRJ)) {
			if (bean.getResult("ro") == null) {
				h_errors.put(ActObjsOptsConst.RES_PRJ, "err.resu_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.KEYWORDS)) {
			if (bean.getKeywords("ro") == null) {
				h_errors.put(ActObjsOptsConst.KEYWORDS, "err.keywrds_req");
			}
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);

			return false;
		}

		return true;
	}

	public void page5(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();

		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
			  application);

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE5).forward(request, response);

			return;
		}

		if ("remove_ben_orgs".equals(action)) {
			String[] ben_orgs_ids = request.getParameterValues("benorg_id");
			removeOrganizations(bean, ben_orgs_ids, session, key,
				  OrganizationRole.BENEFICIARS_ORG_ROLE);
			response.sendRedirect("editActivity?page=5&key=" + key);

			return;
		}

		if ("remove_ben_pers".equals(action)) {
			String[] ben_pers_ids = request.getParameterValues("benpers_id");
			removePersons(bean, ben_pers_ids, session, key,
				  OrganizationRole.BENEFICIARS_ORG_ROLE);
			response.sendRedirect("editActivity?page=5&key=" + key);

			return;
		}

		if ("remove_bens".equals(action)) {
			int[] idxs = getParaInts(request, "ben_idxs");
			Arrays.sort(idxs);
			for (int i = idxs.length - 1; i >= 0; i--) {
				int idx = idxs[i];
				bean.getBeneficiaries().remove(idx);
			}
			response.sendRedirect("editActivity?page=5&key=" + key);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			String description = HttpUtils.getValidTrimedString(request,
				  "desc", null);
			bean.setDescription(lang_bean.language, description);

			String objectives = HttpUtils.getValidTrimedString(request,
				  "pr_obj", null);
			bean.setObjective(lang_bean.language, objectives);

			String results = HttpUtils.getValidTrimedString(request, "rez_prj",
				  null);
			bean.setResult(lang_bean.language, results);

			String keywords = HttpUtils.getValidTrimedString(request,
				  "keyw_prj", null);
			bean.setKeywords(lang_bean.language, keywords);

			String ben_comments = HttpUtils.getValidTrimedString(request, "bencomm", null);
			bean.setBencomment(lang_bean.language, ben_comments);

			// ma uit dupa persoane si organizatii
			// daca gasesc raman pe pagina asta
			String after_selector = HttpUtils.getValidTrimedString(request,
				  "after_selector", null);

			if (after_selector != null) {
				if ("orgs".equals(after_selector)) {
					ArrayList v_orgs = (ArrayList) session.getAttribute("SelectedOrgs");
					session.removeAttribute("SelectedOrgs");

					if (v_orgs != null) {
						OrganizationInv[] orgs = OrganizationInv.buildOrgInvArray(v_orgs,
							  OrganizationRole.BENEFICIARS_ORG_ROLE);

						if (orgs != null) {
							bean.addOrgs(orgs,
								  OrganizationRole.BENEFICIARS_ORG_ROLE);
						}
					}
				} else if ("pers".equals(after_selector)) {
					Person v_person = (Person) session.getAttribute(Person.SELECTED);

					if (v_person != null) {
						PersonInv pi = new PersonInv(v_person,
							  OrganizationRole.getCachedByLocalId(OrganizationRole.BENEFICIARS_ORG_ROLE));
						bean.getPersons_involved().add(pi);
					}
					session.removeAttribute(Person.SELECTED);
				} else if ("benz".equals(after_selector)) {
					String selector_data = HttpUtils.getValidTrimedString(request, "selector_data", null);
					System.out.println("selector_data:" + selector_data);
					long[] ids = getIds(selector_data);
					PropertyListDB propdb = PropertyListDB.getManager(application);
					if (ids != null) {
						for (int i = 0; i < ids.length; i++) {
							try {
								PropertyListItem item = propdb.getItemById(ids[i]);
								if (!bean.containsBeneficiary(item.getId())) {
									System.out.println("added");
									bean.getBeneficiaries().add(item);
								}
							} catch (SQLException e) {
								e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
							}
						}
					}
				}

				response.sendRedirect("editActivity?page=5&key=" + key);

				return;
			}

			if (!isPage5Valid(ed_ctx, bean)) {
				response.sendRedirect("editActivity?page=5&key=" + key);

				return;
			}

			String preview_data = Utils.getValidTrimedString(request,
				  "preview_data", null);

			if ("true".equals(preview_data)) {
				//                request.setAttribute( PNAME_SCREEN, SCREEN_CONFIRM );
				//                request.getRequestDispatcher( JSP_PAGE ).forward( request, response );
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			// nu a selectat orgs sau pers, asa ca trec la urmatoarea pagina
			response.sendRedirect("editActivity?page=6&key=" + key);

			return;
		}
	}

	private int[] getParaInts(HttpServletRequest request, String para_name) {
		int[] result = new int[0];
		String[] values = request.getParameterValues(para_name);
		if (values == null) return result;
		for (int i = 0; i < values.length; i++) {
			String value = values[i];
			int val = -1;
			try {
				val = Integer.parseInt(value);
			} catch (Exception ex) {

			}
			if (val != -1) {
				int[] new_res = new int[result.length + 1];
				System.arraycopy(result, 0, new_res, 0, result.length);
				new_res[result.length] = val;
				result = new_res;
			}
		}
		return result;
	}

	private boolean isPage6Valid(Hashtable ed_ctx, Activity bean) {
		ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
		Hashtable h_errors = new Hashtable();

		if (aoo.isMandatory(ActObjsOptsConst.OTHER_PERS)) {
			PersonInv[] pers = bean.getPersonsByLRId(OrganizationRole.NO_ROLE);

			if ((pers == null) || (pers.length < 1)) {
				h_errors.put(ActObjsOptsConst.OTHER_PERS, "err.othpers_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.DOCUMENTS)) {
			AIDADocument[] docs = bean.getDocuments();

			if ((docs == null) || (docs.length < 1)) {
				h_errors.put(ActObjsOptsConst.DOCUMENTS, "err.docs_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.RESOURCES)) {
			AidaResource[] resources = bean.getResources();

			if ((resources == null) || (resources.length < 1)) {
				h_errors.put(ActObjsOptsConst.RESOURCES, "err.res_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.LOGO)) {
			if (bean.getLogo_url() == null) {
				h_errors.put(ActObjsOptsConst.LOGO, "err.logo_req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CNAME)) {
			if (bean.getContact().getcName() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CNAME, "err.cnamereq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CTITLE)) {
			if (bean.getContact().getcTitle() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CTITLE, "err.ctitlereq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CEMAIL)) {
			if (bean.getContact().getcEmail() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CEMAIL, "err.cemailreq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CCOUNTRY)) {
			if (bean.getContact().getCountry_iso3() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CCOUNTRY,
					  "err.ccountryreq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CADDR1)) {
			if (bean.getContact().getAddr1() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CADDR1, "err.caddr1req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CADDR2)) {
			if (bean.getContact().getAddr2() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CADDR2, "err.caddr2req");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CPZIP)) {
			if (bean.getContact().getPostalZip() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CPZIP, "err.cpzipreq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CPHONE)) {
			if (bean.getContact().getcPhone() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CPHONE, "err.cphonereq");
			}
		}

		if (aoo.isMandatory(ActObjsOptsConst.PROJECT_CURL)) {
			if (bean.getContact().getcURL() == null) {
				h_errors.put(ActObjsOptsConst.PROJECT_CURL, "err.curlreq");
			}
		}

		if (h_errors.size() > 0) {
			ed_ctx.put(PNAME_HERRORS, h_errors);

			return false;
		}

		return true;
	}

	public void page6(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
			  application);

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE6).forward(request, response);

			return;
		}

		bean.setInfoSource(HttpUtils.getValidTrimedString(request, "infosource", null));

		if ("remove_source_orgs".equals(action)) {
			String[] ben_orgs_ids = request.getParameterValues("sourceorg_id");
			removeOrganizations(bean, ben_orgs_ids, session, key,
				  OrganizationRole.DATASOURCE_ORG_ROLE);
			response.sendRedirect("editActivity?page=6&key=" + key);

			return;
		}

		if ("remove_oth_pers".equals(action)) {
			String[] ben_pers_ids = request.getParameterValues("othpers_id");
			removePersons(bean, ben_pers_ids, session, key,
				  OrganizationRole.NO_ROLE);
			response.sendRedirect("editActivity?page=6&key=" + key);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
//                  AidaResource[] resources = bean.getResources();

//                  if ( resources != null )
//                  {
//                        for ( int i = 0; i < resources.length; i++ )
//                        {
//                              resources[ i ].setDesc( lang_bean.language,
//                                    HttpUtils.getValidTrimedString( request, "resdesc" + i,
//                                          null ) );
//
//                              String link = HttpUtils.getValidTrimedString( request,
//                                    "reslink" + i, null );
//
//                              if ( link != null )
//                              {
//                                    if ( !link.toUpperCase().startsWith( "HTTP://" ) )
//                                    {
//                                          link = "http://" + link;
//                                    }
//                              }
//
//                              resources[ i ].setLink( link );
//                        }
//                  }

//                  AIDADocument[] documents = bean.getDocuments();

//                  if ( documents != null )
//                  {
//                        for ( int i = 0; i < documents.length; i++ )
//                              documents[ i ].setDesc( lang_bean.language,
//                                    HttpUtils.getValidTrimedString( request, "docdesc" + i,
//                                          null ) );
//                  }

			ContactInfo contact = bean.getContact();
			contact.setcName(HttpUtils.getValidTrimedString(request, "cname",
				  null));
			contact.setcTitle(HttpUtils.getValidTrimedString(request, "ctitle",
				  null));
			contact.setcEmail(HttpUtils.getValidTrimedString(request, "cemail",
				  null));
			contact.setCountry_iso3(HttpUtils.getValidTrimedString(request,
				  "ccountry", null));
			contact.setAddr1(HttpUtils.getValidTrimedString(request, "caddr1",
				  null));
			contact.setAddr2(HttpUtils.getValidTrimedString(request, "caddr2",
				  null));
			contact.setPostalZip(HttpUtils.getValidTrimedString(request,
				  "pzip", null));
			contact.setcPhone(HttpUtils.getValidTrimedString(request, "cphone",
				  null));
			contact.setcURL(HttpUtils.getValidTrimedString(request, "curl", null));

			// ma uit dupa persoane si organizatii
			// daca gasesc raman pe pagina asta
			String after_selector = HttpUtils.getValidTrimedString(request,
				  "after_selector", null);
			String addres = HttpUtils.getValidTrimedString(request, "addres",
				  null);
			String delres = HttpUtils.getValidTrimedString(request, "delres",
				  null);
			String after_doc_upload = HttpUtils.getValidTrimedString(request,
				  "after_doc_upload", null);
			String after_logo_upload = HttpUtils.getValidTrimedString(request,
				  "after_logo_upload", null);
//               System.out.println( "after doc/logo:" + after_doc_upload + ":" +
//                  after_logo_upload );

			String adddoc = HttpUtils.getValidTrimedString(request, "adddoc",
				  null);
			String deldoc = HttpUtils.getValidTrimedString(request, "deldoc",
				  null);
			String remuploaded = HttpUtils.getValidTrimedString(request,
				  "remuploaded", null);

			if (after_selector != null) {
				if ("pers".equals(after_selector)) {
					Person v_person = (Person) session.getAttribute(Person.SELECTED);

					if (v_person != null) {
						PersonInv pi = new PersonInv(v_person,
							  OrganizationRole.getCachedByLocalId(OrganizationRole.NO_ROLE));
						bean.getPersons_involved().add(pi);
					}
					session.removeAttribute(Person.SELECTED);
				} else if ("sourceorgs".equals(after_selector)) {
					ArrayList v_orgs = (ArrayList) session.getAttribute("SelectedOrgs");
					session.removeAttribute("SelectedOrgs");

					if (v_orgs != null) {
						OrganizationInv[] orgs = OrganizationInv.buildOrgInvArray(v_orgs,
							  OrganizationRole.DATASOURCE_ORG_ROLE);

						if (orgs != null) {
							bean.addOrgs(orgs,
								  OrganizationRole.DATASOURCE_ORG_ROLE);
						}
					}
				}

				response.sendRedirect("editActivity?page=6&key=" + key);

				return;
			} else if (addres != null) {
				String description = HttpUtils.getValidTrimedString(request,
					  "resdesc", null);
				String link = HttpUtils.getValidTrimedString(request,
					  "reslink", null);

				if (link != null) {
					AidaResource resource = new AidaResource();
					resource.setDesc(lang_bean.language, description);
					resource.setLink(link);
					bean.addResource(resource);
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#aresources");

				return;
			} else if (delres != null) {
				String[] values = request.getParameterValues("res_idx");

				if (values != null) {
					java.util.Arrays.sort(values);

					for (int i = values.length - 1; i >= 0; i--) {
						int value = -1;

						try {
							value = Integer.parseInt(values[i]);
						} catch (NumberFormatException nfEx) {
						}

						if (value != -1) {
							bean.removeResource(value);
						}
					}
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#aresources");

				return;
			} else if (after_logo_upload != null) {
				DBFilesPersMan files_pman = DBFilesPersMan.getManager((DBPersistenceToken) PersistenceManager.tokenLookup(getServletContext()));

				String the_box_pname = HttpUtils.getValidTrimedString(request,
					  "uplkey", null);
				Hashtable the_box = (Hashtable) session.getAttribute(the_box_pname);
				session.removeAttribute(the_box_pname);

				try {
					File file = (File) the_box.get(UploadServlet.RESULT_FILE);
					String fileName = (String) the_box.get(UploadServlet.RESULT_FILE_NAME);

					// extension
					String extenstion = ".bmp";
					int lastPoint = fileName.lastIndexOf('.');

					if (lastPoint > 0) {
						extenstion = fileName.substring(lastPoint);
					}

					// extension
					// the generated name
					String name = String.valueOf(System.currentTimeMillis());
					lastPoint = file.getName().lastIndexOf('.');

					if (lastPoint > 0) {
						name = file.getName().substring(0, lastPoint);
					}

					// the generated name
					String dest_rel_path = "/logos/temp/" + name + extenstion;
					if (files_pman.exists(dest_rel_path)) {
						int i = 0;
						dest_rel_path = "/logos/temp/" + i + name + extenstion;
						while (files_pman.exists(dest_rel_path)) {
							i++;
							dest_rel_path = "/logos/temp/" + i + name + extenstion;
						}
					}

					files_pman.saveFile(dest_rel_path, file);
					file.delete();

					if (bean.getLogo_url() != null) {
						try {
							files_pman.deleteFile(bean.getLogo_url());
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					bean.setLogo_url(dest_rel_path);
				} catch (Exception ex) {
					ex.printStackTrace();
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#alogo");

				return;
			} else if (after_doc_upload != null) {
				String the_box_pname = HttpUtils.getValidTrimedString(request,
					  "uplkey", null);
				Hashtable the_box = (Hashtable) session.getAttribute(the_box_pname);
				session.removeAttribute(the_box_pname);

				try {
					File file = (File) the_box.get(UploadServlet.RESULT_FILE);
					String fileName = (String) the_box.get(UploadServlet.RESULT_FILE_NAME);

					// extension
					String extenstion = ".txt";
					int lastPoint = fileName.lastIndexOf('.');

					if (lastPoint > 0) {
						extenstion = fileName.substring(lastPoint);
					}

					// extension
					// the generated name
					String name = String.valueOf(System.currentTimeMillis());
					lastPoint = file.getName().lastIndexOf('.');

					if (lastPoint > 0) {
						name = file.getName().substring(0, lastPoint);
					}

					// the generated name
					File dir = new File(application.getRealPath("/documents/temp/"));

					if (!dir.exists()) {
						dir.mkdirs();
					}

					File newFile = new File(dir, name + extenstion);

					UploadServlet.copy(file, newFile, false);
					the_box.put(UploadServlet.RESULT_FILE, newFile);
					file.delete();
					ed_ctx.put(PNAME_UPLOADED_FILE_BOX, the_box);
				} catch (Exception ex) {
					ex.printStackTrace();
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#adocs");

				return;
			} else if (adddoc != null) {
				String desc = HttpUtils.getValidTrimedString(request,
					  "docdesc", null);
				Hashtable filebox = (Hashtable) ed_ctx.get(PNAME_UPLOADED_FILE_BOX);

				if ((filebox == null) || (desc == null)) {
					response.sendRedirect("editActivity?page=6&key=" + key +
						  "&#adocs");

					return;
				}

				ed_ctx.remove(PNAME_UPLOADED_FILE_BOX);

				AIDADocument document = new AIDADocument();
				File file = (File) filebox.get(UploadServlet.RESULT_FILE);
				String fileName = (String) filebox.get(UploadServlet.RESULT_FILE_NAME);
				document.setDesc(lang_bean.language, desc);
				document.setName(fileName);
				document.setRelativeLink("/documents/temp/" + file.getName());

				bean.addDocument(document);

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#adocs");

				return;
			} else if (deldoc != null) {
				String[] values = request.getParameterValues("doc_idx");

				if (values != null) {
					java.util.Arrays.sort(values);

					for (int i = values.length - 1; i >= 0; i--) {
						int value = -1;

						try {
							value = Integer.parseInt(values[i]);
						} catch (NumberFormatException nfEx) {
						}

						if (value != -1) {
							AIDADocument doc = bean.getDocuments()[value];

							if (doc.getRelativeLink() != null) {
								try {
									DBFilesPersMan files_pman = DBFilesPersMan.getManager((DBPersistenceToken) PersistenceManager.tokenLookup(getServletContext()));
									files_pman.deleteFile(doc.getRelativeLink());
//                                                      File file = new File( application.getRealPath( doc.getRelativeLink() ) );
//
//                                                      if ( file.exists() ) {
//                                                            file.delete();
//                                                      }
								} catch (Exception ex) {
									ex.printStackTrace();
								}
							}
							bean.removeDocument(value);
						}
					}
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#adocs");

				return;
			} else if (remuploaded != null) {
				Hashtable filebox = (Hashtable) ed_ctx.get(PNAME_UPLOADED_FILE_BOX);

				if (filebox == null) {
					response.sendRedirect("editActivity?page=6&key=" + key +
						  "&#adocs");

					return;
				}

				ed_ctx.remove(PNAME_UPLOADED_FILE_BOX);

				try {
					File file = (File) filebox.get(UploadServlet.RESULT_FILE);
					file.delete();
				} catch (Exception ex) {
					ex.printStackTrace();
				}

				response.sendRedirect("editActivity?page=6&key=" + key +
					  "&#adocs");

				return;
			}

			if (!isPage6Valid(ed_ctx, bean)) {
				// nu a selectat orgs sau pers, asa ca trec la urmatoarea pagina
				response.sendRedirect("editActivity?page=6&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			// nu a selectat orgs sau pers, asa ca trec la urmatoarea pagina
			ActivityObjectsOptions aoo = ActivityObjectsOptions.getInstance();
			if (aoo.isEnabled(ActObjsOptsConst.NOTEFIELDS)) {
				response.sendRedirect("editActivity?page=7&key=" + key);
			} else {
				response.sendRedirect("editActivity?page=preview&key=" + key);
			}

			return;
		}
	}

	private boolean isPage7Valid(Hashtable ed_ctx, Activity bean) {
		return true;
	}

	private void page7(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();

		LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
			  application);

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		String key = (String) request.getAttribute(PNAME_KEY);

		String action = Utils.getValidTrimedString(request, PNAME_ACTION,
			  ACTION_EDIT);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (ACTION_EDIT.equals(action)) {
			request.setAttribute(PNAME_SCREEN, SCREEN_EDIT);
			request.getRequestDispatcher(JSP_PAGE7).forward(request, response);

			return;
		}

		if (ACTION_SUBMIT.equals(action)) {
			String notefield1 = HttpUtils.getValidTrimedString(request,
				  "notefield1", null);
			bean.setNoteField1(lang_bean.language, notefield1);

			String notefield2 = HttpUtils.getValidTrimedString(request,
				  "notefield2", null);
			bean.setNoteField2(lang_bean.language, notefield2);

			String notefield3 = HttpUtils.getValidTrimedString(request,
				  "notefield3", null);
			bean.setNoteField3(lang_bean.language, notefield3);

			String notefield4 = HttpUtils.getValidTrimedString(request,
				  "notefield4", null);
			bean.setNoteField4(lang_bean.language, notefield4);

			if (!isPage7Valid(ed_ctx, bean)) {
				response.sendRedirect("editActivity?page=preview&key=" + key);

				return;
			}

			String jumper = Utils.getValidTrimedString(request, "prj_jump", null);

			if (jumper != null) {
				response.sendRedirect("editActivity?page=" + jumper + "&key=" +
					  key);

				return;
			}

			response.sendRedirect("editActivity?page=preview&key=" + key);

			return;
		}

	}

	/**
	 * confirmation page
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void page_preview(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		request.setAttribute(PNAME_SCREEN, SCREEN_CONFIRM);
		request.getRequestDispatcher(JSP_PAGE).forward(request, response);

		return;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		doGet(request, response);
	}

	public void save(HttpServletRequest request, HttpServletResponse response)
		  throws IOException, ServletException {
		ServletContext application = this.getServletContext();
		DBPersistenceToken token = (DBPersistenceToken) DBPersistenceManager.tokenLookup(application);
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(UserConstants.LOGGED_USER);

		Arbiter ab = Arbiter.getManager(token);

		if (user == null) {
			session.invalidate();
			response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED,
				  "User is null");

			return;
		}

		IIDGenerator idGenerators = token.getIdgenerators();

		Hashtable ed_ctx = (Hashtable) request.getAttribute(PNAME_R_CTX);
		Activity bean = (Activity) ed_ctx.get(PNAME_BEAN);

		if (bean == null) {
//               System.out.println( "bean null ?? " );
			response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);

			return;
		}

		// OBJECT STUFF
		AIDAActivityObject object = bean.getObject();

		long current_date = System.currentTimeMillis();

		if (object == null) {
			object = new AIDAActivityObject();
			object.setUser_id(user.getId());
			object.setDate_modif(current_date);

			// de setat atributele object... deocamdata nu sint
			bean.setObject(object);
		}

		// DOCUMENTS STUFF
		// @todo
		// de mutat fisierele din temporar in permanent
		if (bean.getId() == -1) {
			long user_id = user.getId();

			// INSERT
			try {
				object.setId(idGenerators.nextVal(Constants.IDGEN_OBJECTS));

				long act_id = object.getId();
				bean.setId(act_id);
				ActivityDB.getManager(token).insert(bean);

				//approval send
				object.setActivityId(act_id);
				object.setDate_modif(current_date);
				AIDAActivityObjectDB.getManager(token).insert(idGenerators,
					  object);

				GenericActivityProperty titles = bean.getGen_titles();
				titles.setActivityId(act_id);

				if (titles.getUser_id() == -1) {
					titles.setUser_id(user_id);
				}

				titles.setDate_modif(current_date);

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  titles, "gen_titles");

				GenericActivityProperty ext_reasons = bean.getGen_ext_reasons();
				ext_reasons.setActivityId(act_id);
				ext_reasons.setDate_modif(current_date);

				if (ext_reasons.getUser_id() == -1) {
					ext_reasons.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  ext_reasons, "gen_ext_reasons");

				GenericActivityProperty descriptions = bean.getGen_descriptions();
				descriptions.setActivityId(act_id);
				descriptions.setDate_modif(current_date);

				if (descriptions.getUser_id() == -1) {
					descriptions.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  descriptions, "gen_descriptions");

				// begin of notefield1
				GenericActivityProperty note_field1 = bean.getGen_notefield1();
				note_field1.setActivityId(act_id);
				note_field1.setDate_modif(current_date);

				if (note_field1.getUser_id() == -1) {
					note_field1.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  note_field1, "gen_notefields1");
				// end of notefield1
				// begin of notefield2
				GenericActivityProperty note_field2 = bean.getGen_notefield2();
				note_field2.setActivityId(act_id);
				note_field2.setDate_modif(current_date);

				if (note_field2.getUser_id() == -1) {
					note_field2.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  note_field2, "gen_notefields2");
				// end of notefield2
				// begin of notefield3
				GenericActivityProperty note_field3 = bean.getGen_notefield3();
				note_field3.setActivityId(act_id);
				note_field3.setDate_modif(current_date);

				if (note_field3.getUser_id() == -1) {
					note_field3.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  note_field3, "gen_notefields3");
				// end of notefield3
				// begin of notefield4
				GenericActivityProperty note_field4 = bean.getGen_notefield4();
				note_field4.setActivityId(act_id);
				note_field4.setDate_modif(current_date);

				if (note_field4.getUser_id() == -1) {
					note_field4.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  note_field4, "gen_notefields4");
				// end of notefield4

				GenericActivityProperty objectives = bean.getGen_objectives();
				objectives.setActivityId(act_id);
				objectives.setDate_modif(current_date);

				if (objectives.getUser_id() == -1) {
					objectives.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  objectives, "gen_objectives");

				GenericActivityProperty results = bean.getGen_results();
				results.setActivityId(act_id);
				results.setDate_modif(current_date);

				if (results.getUser_id() == -1) {
					results.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  results, "gen_results");

				GenericActivityProperty status_reasons = bean.getGen_status_reasons();
				status_reasons.setActivityId(act_id);
				status_reasons.setDate_modif(current_date);

				if (status_reasons.getUser_id() == -1) {
					status_reasons.setUser_id(user_id);
				}

				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  status_reasons, "gen_status");

				GenericActivityProperty keywords = bean.getGen_keywords();
				keywords.setActivityId(act_id);
				keywords.setDate_modif(current_date);
				if (keywords.getUser_id() == -1) {
					keywords.setUser_id(user_id);
				}
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  keywords, "gen_keywords");

				GenericActivityProperty bencomments = bean.getGen_bencomment();
				bencomments.setActivityId(act_id);
				bencomments.setDate_modif(current_date);
				if (bencomments.getUser_id() == -1) {
					bencomments.setUser_id(user_id);
				}
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  bencomments, "gen_bencomments");

				GenericActivityProperty[] components = bean.getComponents();

				if (components == null) {
					components = new GenericActivityProperty[0];
				}

				for (int i = 0; i < components.length; i++) {
					components[i].setActivityId(act_id);
					components[i].setDate_modif(current_date);

					if (components[i].getUser_id() == -1) {
						components[i].setUser_id(user_id);
					}

					GenericActivityPropertyDB.getManager(token).insert(idGenerators,
						  components[i], "gen_components");
				}

				OrganizationInv[] organizations = bean.getOrganizations();

				if (organizations == null) {
					organizations = new OrganizationInv[0];
				}

				for (int i = 0; i < organizations.length; i++) {
					organizations[i].setActivityId(act_id);
					organizations[i].setDate_modif(current_date);

					if (organizations[i].getUser_id() == -1) {
						organizations[i].setUser_id(user_id);
					}

					OrganizationInvDB oinv = OrganizationInvDB.getManager(token);
					oinv.insert(idGenerators, organizations[i]);
				}

				PersonInv[] persons = bean.getPersons();

				if (persons == null) {
					persons = new PersonInv[0];
				}

				for (int i = 0; i < persons.length; i++) {
					persons[i].setActivityId(act_id);
					persons[i].setDate_modif(current_date);

					if (persons[i].getUser_id() == -1) {
						persons[i].setUser_id(user_id);
					}

					PersonInvDB.getManager(token).insert(idGenerators,
						  persons[i]);
				}

				AIDADocument[] documents = bean.getDocuments();

				if (documents == null) {
					documents = new AIDADocument[0];
				}

				for (int i = 0; i < documents.length; i++) {
					documents[i].setActivityId(act_id);
					documents[i].setDate_modif(current_date);

					if (documents[i].getUser_id() == -1) {
						documents[i].setUser_id(user_id);
					}

					AIDADocumentDB.getManager(token).insert(idGenerators,
						  documents[i]);
					DBFilesPersMan.getManager(token).publishFile(documents[i].getRelativeLink());
				}

				AidaResource[] resources = bean.getResources();

				if (resources == null) {
					resources = new AidaResource[0];
				}

				for (int i = 0; i < resources.length; i++) {
					resources[i].setActivityId(act_id);
					resources[i].setDate_modif(current_date);

					if (resources[i].getUser_id() == -1) {
						resources[i].setUser_id(user_id);
					}

					AIDAResourceDB.getManager(token).insert(idGenerators,
						  resources[i]);
				}

				DBStuff.getManager(token).insertDonorIds(bean);

				AIDALocation[] locations = bean.getLocations();

				if (locations == null) {
					locations = new AIDALocation[0];
				}

				for (int i = 0; i < locations.length; i++) {
					locations[i].setActivityId(act_id);
					locations[i].setDate_modif(current_date);

					if (locations[i].getUser_id() == -1) {
						locations[i].setUser_id(user_id);
					}

					AIDALocationDB.getManager(token).insertLocation(locations[i]);
				}

				AIDAObjSector[] sectors = bean.getSectors();

				if (sectors == null) {
					sectors = new AIDAObjSector[0];
				}

				for (int i = 0; i < sectors.length; i++) {
					sectors[i].setActivityId(act_id);
					sectors[i].setDate_modif(current_date);

					if (sectors[i].getUser_id() == -1) {
						sectors[i].setUser_id(user_id);
					}

					AIDAObjSectorDB.getManager(token).insert(sectors[i]);
				}

				FundingItem[] funding_items = bean.getFunding_itemsArray();

				if (funding_items == null) {
					funding_items = new FundingItem[0];
				}

				for (int i = 0; i < funding_items.length; i++) {
					funding_items[i].setActivityId(act_id);

					//                              funding_items[ i ].setUser_id( bean.getObject().getUser_id() );
					funding_items[i].setDate_modif(current_date);

					if (funding_items[i].getUser_id() == -1) {
						funding_items[i].setUser_id(user_id);
					}

					FndPersMan.getManager(token).insert(funding_items[i]);
				}

				ActivityRelation[] relations = bean.getAct_relationsArray();

				if (relations == null) {
					relations = new ActivityRelation[0];
				}

				for (int i = 0; i < relations.length; i++) {
					relations[i].setActivity_id(act_id);
				}

				bean.make_simetric_relations();
				relations = bean.getAct_relationsArray();
				ActivityRelationDB.getManager(token).insert(relations);

				DBStuff.getManager(token).insert_act_cats_links(bean);

				ContactInfoPMan.getManager(token).insert(bean.getContact());
				DBFilesPersMan.getManager(token).publishFile(bean.getLogo_url());

				ActivityDB.getManager(token).setBeneficiaries(bean);

				Event e = ab.createEvent(user.getId(), bean.getId(),
					  Arbiter.PROJECT_TYPE, Event.ALERT);
				ab.deployApprovals(user.getId(), bean.getId(),
					  Arbiter.PROJECT_TYPE, e);

				AlertDispacher ad = new AlertDispacher(token, bean);
				ad.sendAlerts(e);
			} catch (Exception sqlEx) {
				sqlEx.printStackTrace();
			}
		} else {
			// UPDATE
			try {
				long id = bean.getId();
				long user_id = bean.getObject().getUser_id();

				DBStuff.getManager(token).deleteDonorIdsForActivity(id);

				AIDAActivityObjectDB.getManager(token).delete(id);
				ContactInfoPMan.getManager(token).removeForActivity(id);

				//ab.track((int)user_id,(int)act_id,Arbiter.PROJECT_TYPE);
				ActivityRelationDB.getManager(token).delete_for_activity(id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_titles",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_ext_reasons",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_descriptions",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields1",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields2",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields3",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields4",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_objectives",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_results",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_status",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_keywords",
					  id);
				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_bencomments",
					  id);

				GenericActivityProperty[] components = bean.getComponents();

				if (components == null) {
					components = new GenericActivityProperty[0];
				}

				GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_components",
					  id);

				OrganizationInv[] organizations = bean.getOrganizations();

				if (organizations == null) {
					organizations = new OrganizationInv[0];
				}

				OrganizationInvDB oidb = OrganizationInvDB.getManager(token);
				oidb.deleteForActivity(id);

				PersonInv[] persons = bean.getPersons();

				if (persons == null) {
					persons = new PersonInv[0];
				}

				PersonInvDB.getManager(token).deleteForActivity(id);

				AIDADocument[] documents = bean.getDocuments();

				if (documents == null) {
					documents = new AIDADocument[0];
				}

				AIDADocumentDB.getManager(token).deleteForActivity(id);

				AidaResource[] resources = bean.getResources();

				if (resources == null) {
					resources = new AidaResource[0];
				}

				AIDAResourceDB.getManager(token).delete_for_activity(id);

				AIDALocation[] locations = bean.getLocations();

				if (locations == null) {
					locations = new AIDALocation[0];
				}

				AIDALocationDB.getManager(token).delete_for_activity(id);

				AIDAObjSector[] sectors = bean.getSectors();

				if (sectors == null) {
					sectors = new AIDAObjSector[0];
				}

				AIDAObjSectorDB.getManager(token).delete_for_activity(id);

				FundingItem[] funding_items = bean.getFunding_itemsArray();

				if (funding_items == null) {
					funding_items = new FundingItem[0];
				}

				FndPersMan.getManager(token).deleteForActivity(id);

				DBStuff.getManager(token).delete_cats_for_activity(id);
				DBStuff.getManager(token).delete_objects(id);
				ActivityDB.getManager(token).deleteBeneficiaries(bean);
				ActivityDB.getManager(token).delete(id);

				// end delete
				long act_id = object.getId();
				object.setDate_modif(current_date);

				ActivityDB.getManager(token).insert(bean);
				AIDAActivityObjectDB.getManager(token).insert(idGenerators,
					  object);

				GenericActivityProperty titles = bean.getGen_titles();
				titles.setActivityId(act_id);
				titles.setUser_id(user_id);
				titles.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  titles, "gen_titles");

				GenericActivityProperty ext_reasons = bean.getGen_ext_reasons();
				ext_reasons.setActivityId(act_id);
				ext_reasons.setUser_id(user_id);
				ext_reasons.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  ext_reasons, "gen_ext_reasons");

				GenericActivityProperty descriptions = bean.getGen_descriptions();
				descriptions.setActivityId(act_id);
				descriptions.setUser_id(user_id);
				descriptions.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  descriptions, "gen_descriptions");

				GenericActivityProperty notefield1 = bean.getGen_notefield1();
				notefield1.setActivityId(act_id);
				notefield1.setUser_id(user_id);
				notefield1.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  notefield1, "gen_notefields1");

				GenericActivityProperty notefield2 = bean.getGen_notefield2();
				notefield2.setActivityId(act_id);
				notefield2.setUser_id(user_id);
				notefield2.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  notefield2, "gen_notefields2");

				GenericActivityProperty notefield3 = bean.getGen_notefield3();
				notefield3.setActivityId(act_id);
				notefield3.setUser_id(user_id);
				notefield3.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  notefield3, "gen_notefields3");

				GenericActivityProperty notefield4 = bean.getGen_notefield4();
				notefield4.setActivityId(act_id);
				notefield4.setUser_id(user_id);
				notefield4.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  notefield4, "gen_notefields4");

				GenericActivityProperty objectives = bean.getGen_objectives();
				objectives.setActivityId(act_id);
				objectives.setUser_id(user_id);
				objectives.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  objectives, "gen_objectives");

				GenericActivityProperty results = bean.getGen_results();
				results.setActivityId(act_id);
				results.setUser_id(user_id);
				results.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  results, "gen_results");

				GenericActivityProperty status_reasons = bean.getGen_status_reasons();
				status_reasons.setActivityId(act_id);
				status_reasons.setUser_id(user_id);
				status_reasons.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  status_reasons, "gen_status");

				GenericActivityProperty keywords = bean.getGen_keywords();
				keywords.setActivityId(act_id);
				keywords.setUser_id(user_id);
				keywords.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  keywords, "gen_keywords");

				GenericActivityProperty bencomments = bean.getGen_bencomment();
				bencomments.setActivityId(act_id);
				bencomments.setUser_id(user_id);
				bencomments.setDate_modif(current_date);
				GenericActivityPropertyDB.getManager(token).insert(idGenerators,
					  bencomments, "gen_bencomments");

				for (int i = 0; i < components.length; i++) {
					components[i].setActivityId(act_id);
					components[i].setUser_id(user_id);
					components[i].setDate_modif(current_date);
					GenericActivityPropertyDB.getManager(token).insert(idGenerators,
						  components[i], "gen_components");
				}

				for (int i = 0; i < organizations.length; i++) {
					organizations[i].setActivityId(act_id);
					organizations[i].setUser_id(user_id);
					organizations[i].setDate_modif(current_date);

					OrganizationInvDB oinv = OrganizationInvDB.getManager(token);
					oinv.insert(idGenerators, organizations[i]);
				}

				for (int i = 0; i < persons.length; i++) {
					persons[i].setActivityId(act_id);
					persons[i].setUser_id(user_id);
					persons[i].setDate_modif(current_date);
					PersonInvDB.getManager(token).insert(idGenerators,
						  persons[i]);
				}

				for (int i = 0; i < documents.length; i++) {
					documents[i].setActivityId(act_id);
					documents[i].setUser_id(user_id);
					documents[i].setDate_modif(current_date);
					AIDADocumentDB.getManager(token).insert(idGenerators,
						  documents[i]);
					DBFilesPersMan.getManager(token).publishFile(documents[i].getRelativeLink());
				}

				for (int i = 0; i < resources.length; i++) {
					resources[i].setActivityId(act_id);
					resources[i].setUser_id(user_id);
					resources[i].setDate_modif(current_date);
					AIDAResourceDB.getManager(token).insert(idGenerators,
						  resources[i]);
				}

				DBStuff.getManager(token).insertDonorIds(bean);

				for (int i = 0; i < locations.length; i++) {
					locations[i].setActivityId(act_id);
					locations[i].setUser_id(user_id);
					locations[i].setDate_modif(current_date);
					AIDALocationDB.getManager(token).insertLocation(locations[i]);
				}

				for (int i = 0; i < sectors.length; i++) {
					sectors[i].setActivityId(act_id);
					sectors[i].setUser_id(user_id);
					sectors[i].setDate_modif(current_date);
					AIDAObjSectorDB.getManager(token).insert(sectors[i]);
				}

				for (int i = 0; i < funding_items.length; i++) {
					funding_items[i].setActivityId(act_id);
					funding_items[i].setUser_id(user_id);
					funding_items[i].setDate_modif(current_date);

					//                              System.out.println( "status:" + funding_items[i].getStatus().getName("EN") );
					//                              System.out.println( "id:" + funding_items[i].getId() );
					//                              System.out.println( "org:" + funding_items[i].getOrg_id() );
					FndPersMan.getManager(token).insert(funding_items[i]);
				}

				ActivityRelation[] relations = bean.getAct_relationsArray();

				if (relations == null) {
					relations = new ActivityRelation[0];
				}

				for (int i = 0; i < relations.length; i++)
					relations[i].setActivity_id(act_id);

				bean.make_simetric_relations();
				relations = bean.getAct_relationsArray();
				ActivityRelationDB.getManager(token).insert(relations);

				DBStuff.getManager(token).insert_act_cats_links(bean);
				ContactInfoPMan.getManager(token).insert(bean.getContact());
				DBFilesPersMan.getManager(token).publishFile(bean.getLogo_url());

				ActivityDB.getManager(token).setBeneficiaries(bean);

				Event e = ab.createEvent(user.getId(), bean.getId(),
					  Arbiter.PROJECT_TYPE, Event.ALERT);
				ab.deployApprovals(user.getId(), bean.getId(),
					  Arbiter.PROJECT_TYPE, e);


				AlertDispacher ad = new AlertDispacher(token, bean);
				ad.sendAlerts(e);
			} catch (Exception sqlEx) {
				sqlEx.printStackTrace();
			}
		}

		String ctx = request.getContextPath();
		response.sendRedirect(ctx + "/activity/view.jsp?id=" + bean.getId());

		//response.sendRedirect( referer );
		return;
	}

	public static void removeOrganizations(Activity bean, String[] orgs_ids,
								    HttpSession session, String key, Integer orgRole) {
		if (orgs_ids == null) {
			return;
		}

		String selectors_key = "";

		if (orgRole == OrganizationRole.DONOR_ORG_ROLE) {
			selectors_key = "donor";
		} else if (orgRole == OrganizationRole.BENEFICIARS_ORG_ROLE) {
			selectors_key = "ben";
		} else if (orgRole == OrganizationRole.FINANCING_ORG_ROLE) {
			selectors_key = "fin";
		} else if (orgRole == OrganizationRole.CONTRACTING_ORG_ROLE) {
			selectors_key = "con";
		}

		Hashtable orgs_beans = (Hashtable) session.getAttribute(OrgSelectorServlet.PNAME_BEANS);
		Hashtable orgs_bean = (Hashtable) ((orgs_beans == null) ? null
			  : orgs_beans.get(OrgSelectorServlet.PNAME_ORGSELS));
		Vector v_orgs = (Vector) ((orgs_bean == null) ? null
			  : orgs_bean.get(selectors_key +
			  key));

		for (int i = 0; i < orgs_ids.length; i++) {
			long org_id = -1;

			try {
				org_id = new Long(orgs_ids[i]).longValue();
			} catch (NumberFormatException nfEx) {
			}

			if (v_orgs != null) {
				for (int j = 0; j < v_orgs.size(); j++) {
					Organization o = (Organization) v_orgs.elementAt(j);

					if (o.getId() == org_id) {
						v_orgs.remove(j);
						j--;
					}
				}
			}

			bean.removeOrgByRoleId(orgRole, org_id);
			bean.removeFundingItemsForOrg(org_id);
		}

		// selected organizations
	}

	public static boolean searchCheckboxIds(String[] pers_ids, long id) {
		for (int i = 0; i < pers_ids.length; i++) {
			if (id == Long.parseLong(pers_ids[i])) {
				return true;
			}
		}

		return false;
	}

	public static void removePersons(Activity bean, String[] pers_ids,
							   HttpSession session, String key, Integer orgRole) {
		if (pers_ids == null) {
			return;
		}

		ArrayList p_inv = bean.getPersons_involved();

		for (int i = 0; i < p_inv.size(); i++) {
			PersonInv t = (PersonInv) p_inv.get(i);

			if (searchCheckboxIds(pers_ids, t.getPerson_id()) &&
				  (t.getRole().getId().intValue() == orgRole.intValue())) {
				p_inv.remove(t);
			}
		}
	}

	private long[] getIds(String items) {
		if (items == null) return null;
		long[] result = new long[0];
		StringTokenizer st = new StringTokenizer(items, ",");
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			long id = -1;
			try {
				id = Long.parseLong(token);
			} catch (Exception ex) {
			}

			if (id != -1) {
				long[] new_res = new long[result.length + 1];
				System.arraycopy(result, 0, new_res, 0, result.length);
				new_res[result.length] = id;
				result = new_res;
			}
		}

		System.out.println("result:" + result.length);
		return result;
	}

	// mmm tpt
	// astea stau in sessiune
	public static final String ED_CTXS = "eas_contexts";

	// ctx in ctxs
	public static final String PNAME_KEY = "key";
	public static final String PNAME_FIRST_TIME = "eas_first_time";
	public static final String PNAME_REFERER = "eas_ref";
	public static final String PNAME_BEAN = "eas_bean";
	public static final String PNAME_UPLOADED_FILE_BOX = "uploaded_file_box";

	// informatii provizorii pt. faza de dezvoltare
	public static final String PNAME_R_CTX = "eas_ctx";
	public static final String PNAME_EDTYPE = "edtype";
	public static final String EDTYPE_EDIT = "ed";
	public static final String EDTYPE_NEW = "new";
	public static final String EDTYPE_DELETE = "del";
	public static final String PNAME_ACTION = "action";
	public static final String ACTION_EDIT = "edit";
	public static final String ACTION_SUBMIT = "submit";
	public static final String ACTION_SAVE = "save";
	public static final String ACTION_CANCEL = "cancel";
	public static final String PNAME_LAST_ACCESS = "eas_lastaccess";

	//SRK
	public static final String PNAME_TMP_ACTINFO = "tmp_actinfo";

	// jsp screens :P
	public static final String PNAME_SCREEN = "eas_scr";
	public static final String SCREEN_EDIT = "eas_scrEdiT";
	public static final String SCREEN_CONFIRM = "eas_scrconfirm";
	public static final String SCREEN_ERROR = "eas_screrror";
	public static final String PNAME_ERRORS = "eas_pnerr";
	public static final String PNAME_HERRORS = "eas_pnherr";

	// jsp page
	public static final String JSP_PAGE = "editActivity.jsp";
	public static final String JSP_PAGE1 = "page1.jsp";
	public static final String JSP_PAGE2 = "page2.jsp";
	public static final String JSP_PAGE3 = "page3.jsp";
	public static final String JSP_PAGE4 = "page4.jsp";
	public static final String JSP_PAGE5 = "page5.jsp";
	public static final String JSP_PAGE6 = "page6.jsp";
	public static final String JSP_PAGE7 = "page7.jsp";
	public static final String SIGNATURE = "eas_sig_duda";
	public static final String SERVICE_CF = "eas_cf";

	// pt. scroll in html
	public static final String PNAME_SHUST_1 = "zashust1";
	public static final String PV_SHUST_1_SECTOR = "sector_shust";
	public static final String PV_SHUST_1_LOCAL = "local_shust";
}
